import asyncio
from TikTokApi import TikTokApi
import logging

logging.basicConfig(level=logging.INFO)

async def extract_tiktok_video(url: str) -> str:
    try:
        async with TikTokApi() as api:
            # 创建会话（headless 模式）
            await api.create_sessions(num_sessions=1, headless=True)

            # 获取视频对象
            video = api.video(url=url)

            # 获取视频详细信息
            data = await video.info()

            # 视频 ID
            aweme_id = data.get("aweme_id")
            logging.info(f"视频 ID: {aweme_id}")

            # 作者
            author = data.get("author", {}).get("unique_id")
            logging.info(f"作者: {author}")

            # 尝试获取无水印视频地址
            video_url = data.get("video", {}).get("play_addr", {}).get("url_list", [])
            if video_url:
                logging.info(f"无水印视频地址: {video_url[0]}")
                return video_url[0]

            logging.warning("⚠️ 未能获取无水印视频地址")
            return url

    except Exception as e:
        logging.error(f"❌ 提取失败: {e}")
        return url